using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using project.api.Models;

namespace project.api.Tools
{
    /// <summary>
    /// 模拟登录中间件
    /// </summary>
    public class SimulationLogin:IMiddleware
    {
        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {

            var appSettings = (AppSettings) context.RequestServices.GetService(typeof(AppSettings));
            
            var userid = context.Request.Headers["x-userid"].ToString();
            if (!string.IsNullOrEmpty(userid))
            {
                var dict = new Dictionary<string, string>();
                dict.Add("userid", userid);

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Jwt.SigningKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: appSettings.Jwt.Issuer,
                    audience: appSettings.Jwt.Audience,
                    claims: dict.Select(x => new Claim(x.Key, x.Value)),
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: creds);
                var jwt = new JwtSecurityTokenHandler().WriteToken(token);
                context.Request.Headers.Add("Authorization","Bearer "+jwt);
            }

            return next(context);

        }

    }
}